<template>
  <div class="dothings-container">
    <!-- 输入区 -->
    <div class="input-area">
      <el-date-picker v-model="date" type="date" size="large" style="width: 180px;" :editable="false"
        placeholder="选择日期" />
      <el-time-picker v-model="time" size="large" style="width: 220px;" placeholder="选择时间" format="HH:mm:ss"
        value-format="HH:mm:ss" />
      <input v-model="thing" placeholder="要做的事情" class="thing-input" />
      <button @click="addThing" class="el-btn">确定</button>
    </div>
    <!-- 展示区 -->
    <div class="display-area">
      <div class="todo-list">
        <h3>今天</h3>
        <table class="todo-table">
          <thead>
            <tr>
              <th>时间</th>
              <th>事项</th>
              <!-- 表头部分 -->
              <th>已做/未做</th>
              <th>操作</th>

              <!-- 表体部分，假设在循环中渲染每一行 -->
              
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in todayList" :key="item.id">
              <td>{{ item.date }} {{ item.time }}</td>
              <td>
              <el-input 
                v-if="editingId === item.id"
                v-model="editText"
                size="small"
                @keyup.enter="saveEdit(item)"
              />
              <span v-else>{{ item.thing }}</span>
            </td>
              <td>
                <el-button :type="item.done ? 'success' : 'warning'" size="small" @click="toggleDone(item)">{{ item.done ? '已做' : '未做' }}</el-button>
              <td>
                <el-button 
                  type="primary" 
                  size="mini"
                  @click="startEdit(item)"
                >{{ editingId === item.id ? '确定' : '修改' }}</el-button>
                <el-button type="danger" size="mini" @click="deleteThing(item)">删除</el-button>
              </td>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="todo-list">
        <h3>以后</h3>
        <table class="todo-table">
          <thead>
            <tr>
              <th>时间</th>
              <th>事项</th>
              <th>已做/未做</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in futureList" :key="item.id">
              <td>{{ item.date }} {{ item.time }}</td>
              <td>{{ item.thing }}</td>
              <td>
                <el-button :type="item.done ? 'success' : 'warning'" size="small" @click="toggleDone(item)">{{ item.done
                  ? '已做' : '未做' }}</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dothings-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 32px 0;
}

.input-area {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-bottom: 16px;
}

.thing-input {
  width: 220px;
  padding: 10px;
  font-size: 18px;
}

.el-btn {
  padding: 10px 24px;
  font-size: 18px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.display-area {
  display: flex;
  gap: 32px;
  justify-content: center;
}

.todo-list {
  flex: 1;
  background: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
}

.todo-table {
  width: 100%;
  border-collapse: collapse;
}

.todo-table th, .todo-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
  width: 33.33%;
}

.todo-table th {
  background-color: #f0f0f0;
  font-weight: bold;
}

.todo-list > h3 {
  text-align: center;
}
@media (max-width: 700px) {
  .input-area {
    flex-direction: column;
    gap: 12px;
  }
  .thing-input {
    width: 100%;
    padding: 10px 12px;
    font-size: 16px;
    border-radius: 8px;
    border: 1px solid #ccc;
    box-sizing: border-box;
  }
  .el-btn {
    width: 100%;
    margin-top: 8px;
    font-size: 16px;
    border-radius: 8px;
  }
  .display-area {
    flex-direction: column;
    gap: 20px;
  }
  .todo-list {
    width: 100%;
  }
  .todo-table th, .todo-table td {
    font-size: 14px;
    padding: 6px;
  }
  .todo-table th {
    font-weight: 600;
  }
}

.el-time-panel {
  max-height: 300px !important;
  height: 300px !important;
}
</style>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
function getToday() {
  const d = new Date()
  return d.toISOString().slice(0, 10)
}
function getTomorrow() {
  const d = new Date()
  d.setDate(d.getDate() + 1)
  return d.toISOString().slice(0, 10)
}
const date = ref(getToday())
const time = ref('12:00:00')
const thing = ref('')
const list = ref([])
const editingId = ref(null)
const editText = ref('')
let id = 0
function formatDateToYMD(val) {
  if (val instanceof Date) {
    const year = val.getFullYear();
    const month = String(val.getMonth() + 1).padStart(2, '0');
    const day = String(val.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } else if (typeof val === 'string' && val.includes('T')) {
    return val.slice(0, 10);
  } else if (typeof val === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(val)) {
    return val;
  } else {
    try {
      const dateObj = new Date(val);
      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, '0');
      const day = String(dateObj.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    } catch {
      return '';
    }
  }
}

function addThing() {
  if (!thing.value) return
  const dateStr = formatDateToYMD(date.value)
  const newItem = {
    id: id++,
    date: dateStr,
    time: time.value,
    thing: thing.value,
    done: false
  }
  list.value.push(newItem)
  thing.value = ''
}

const todayList = computed(() => {
  const today = formatDateToYMD(getToday())
  return list.value.filter(item => formatDateToYMD(item.date) === today)
})
const futureList = computed(() => {
  const today = formatDateToYMD(getToday())
  return list.value.filter(item => formatDateToYMD(item.date) > today).sort((a, b) => formatDateToYMD(a.date).localeCompare(formatDateToYMD(b.date)))
})
function toggleDone(item) {
  if (!item || item.done === undefined) {
    console.error('Invalid item in toggleDone:', item);
    ElMessage.error('操作失败：无效的事项数据');
    return;
  }
  
  try {
    console.log('Toggling item status:', item.id, 'from', item.done, 'to', !item.done);
    item.done = !item.done;
    
    if (item.done) {
      ElMessage.success('已标记为已做');
      console.log('Item marked as done:', item.id);
    } else {
      ElMessage.warning('已标记为未做');
      console.log('Item marked as not done:', item.id);
    }
  } catch (error) {
    console.error('Error in toggleDone:', error);
    ElMessage.error('操作失败：' + error.message);
  }
}

function startEdit(item) {
  if (editingId.value === item.id) {
    saveEdit(item)
    return
  }
  editingId.value = item.id
  editText.value = item.thing
}

async function saveEdit(item) {
  try {
    if (!editText.value.trim()) {
      ElMessage.warning('事项内容不能为空')
      return
    }
    
    // 调用HTTP模块（假设已存在）
    const response = await http.post('/api/update', {
      id: item.id,
      thing: editText.value,
      date: item.date,
      time: item.time,
      done: item.done
    })

    if (response.data.success) {
      Object.assign(item, {
        thing: editText.value
      })
      ElMessage.success('修改成功')
      editingId.value = null
    }
  } catch (error) {
    console.error('修改失败:', error)
    ElMessage.error(`修改失败: ${error.message}`)
  }
}

// 删除事项函数
function deleteThing(item) {
  try {
    const index = list.value.findIndex(i => i.id === item.id);
    if (index > -1) {
      list.value.splice(index, 1);
      ElMessage.success('删除成功');
      console.log('Deleted item:', item.id);
    } else {
      ElMessage.warning('未找到要删除的事项');
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败: ' + error.message);
  }
}
</script>
